package me.huanmeng.heater.sender;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.base.Joiner;
import me.huanmeng.heater.exception.ResponseException;
import me.huanmeng.heater.http.KaiheilaApi;
import me.huanmeng.heater.main.HeaterMain;
import me.huanmeng.heater.object.ChannelInfo;
import me.huanmeng.heater.object.MessageData;

/**
 * 2021/10/4<br>
 * Heater<br>
 *
 * @author huanmeng_qwq
 */
public class Channel implements Messages {
    private final ChannelInfo channelInfo;

    public Channel(ChannelInfo channelInfo) {
        this.channelInfo = channelInfo;
    }

    @Override
    public MessageData sendMessage(String... lines) {
        final KaiheilaApi kaiheilaApi = HeaterMain.getInstance().getKaiheilaApi();
        //noinspection MismatchedQueryAndUpdateOfCollection
        final JSONObject jsonObject = new JSONObject(kaiheilaApi.doPost("/message/create")
                .form("target_id", channelInfo.getId())
                .form("content", Joiner.on("\n").join(lines)).execute().body());
        if (jsonObject.getInt("code") != 0) {
            throw new ResponseException(jsonObject.toString());
        }
        return JSONUtil.toBean(jsonObject.getJSONObject("data"), MessageData.class);
    }

    public void clearChat(int count){
        final KaiheilaApi kaiheilaApi = HeaterMain.getInstance().getKaiheilaApi();
        final JSONObject jsonObject = new JSONObject(kaiheilaApi.doGet("/message/list")
                .form("target_id", channelInfo.getId())
                .form("page_size",count)
                .executeAsync().body());
        final JSONArray array = (JSONArray) jsonObject.getByPath("data.items");
        for (Object json : array) {
            final String id = ((JSONObject) json).getStr("id");
            final JSONObject resp = new JSONObject(kaiheilaApi.doPost("/message/delete").form("msg_id", id).executeAsync().body());
            if(resp.getInt("code",-1)!=0){
                throw new ResponseException(resp.toString());
            }
        }
    }
}
